<template>
  <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large">
    <el-form-item prop="user">
      <el-input v-model="form.user" prefix-icon="el-icon-user" clearable :placeholder="$t('login.userPlaceholder')">
        <template #append>
          <el-select v-model="userType" style="width: 130px">
            <el-option :label="$t('login.admin')" value="admin"></el-option>
            <el-option :label="$t('login.user')" value="user"></el-option>
          </el-select>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
    </el-form-item>

    <el-form-item prop="captcha">
      <el-col :span="15">
        <el-input ref="codeRef" text maxlength="4" v-model="captchaImageCode" clearable autocomplete="off">
          <template #prefix>
            <el-icon>
              <Position />
            </el-icon>
          </template>
        </el-input>
      </el-col>
      <el-col :span="1"></el-col>
      <el-col :span="8">
        <div class="login-content-code">
          <img class="login-content-code-img" @click="getCaptcha" width="130px" height="38px" :src="captchaImage" style="cursor: pointer" />
        </div>
      </el-col>
    </el-form-item>

    <el-form-item style="margin-bottom: 10px">
      <el-col :span="12">
        <el-checkbox :label="$t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
      </el-col>
      <el-col :span="12" class="login-forgot">
        <router-link to="/reset_password">{{ $t('login.forgetPassword') }}？</router-link>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" style="width: 100%" :loading="islogin" round @click="loginNext">{{ $t('login.signIn') }}</el-button>
    </el-form-item>
    <div class="login-reg">
      {{ $t('login.noAccount') }}
      <router-link to="/user_register">{{ $t('login.createAccount') }}</router-link>
    </div>
  </el-form>
  <!--
	<el-dialog
		v-model="dialogVisible"
		:before-close="handleClose"
		width="24%"
		class="captcha_card"
	>
		<captcha @onsuccess="captchaSuccess" />
	</el-dialog>-->
</template>

<script>
// import Captcha from "./captcha.vue";
import { Position } from '@element-plus/icons-vue';
export default {
  components: {
    // Captcha,
    Position,
  },
  data() {
    return {
      userType: 'admin',
      form: {
        user: 'xiehanbing',
        password: '123456',
        autologin: false,
      },
      rules: {
        user: [
          {
            required: true,
            message: this.$t('login.userError'),
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: this.$t('login.PWError'),
            trigger: 'blur',
          },
        ],
      },
      islogin: false,
      captchaState: undefined,
      captchaImage: null,
      captchaCheckId: '',
      captchaImageCode: '',
      dialogVisible: false,
    };
  },
  watch: {
    userType(val) {
      if (val == 'admin') {
        this.form.user = 'xiehanbing';
        this.form.password = '123456';
      } else if (val == 'user') {
        this.form.user = 'user';
        this.form.password = 'user';
      }
    },
  },
  mounted() {
    this.getCaptcha();
  },
  methods: {
    async loginNext() {
      await this.login();
    },
    async login() {
      var validate = await this.$refs.loginForm.validate().catch(() => {});
      if (!validate) {
        return false;
      }

      this.islogin = true;
      var data = {
        account: this.form.user,
        password: this.form.password,
        code: this.captchaImageCode,
        checkCodeId: this.captchaCheckId,
      };
      //获取token
      var user = await this.$API.auth.token.post(data).catch(() => {
        this.islogin = false;
        this.getCaptcha();
      });
      if (user == undefined) return;
      if (user.code == 200) {
        this.$TOOL.cookie.set('TOKEN', user.data.token, {
          expires: this.form.autologin ? 24 * 60 * 60 : 0,
        });
        this.$TOOL.data.set('USER_INFO', user.data.userInfo);
      } else {
        this.islogin = false;
        this.$message.warning(user.message);
        this.captchaImageCode = '';
        this.getCaptcha();
        return false;
      }
      //获取菜单
      var menu = null;
      if (this.userType == 'admin') {
        menu = await this.$API.system.menu.myMenus.get();
      } else {
        menu = await this.$API.demo.menu.get();
      }
      if (menu.code == 200) {
        if (menu.data.menu.length == 0) {
          this.islogin = false;
          this.$alert('当前用户无任何菜单权限，请联系系统管理员', '无权限访问', {
            type: 'error',
            center: true,
          });
          return false;
        }
        this.$TOOL.data.set('MENU', menu.data.menu);
        this.$TOOL.data.set('PERMISSIONS', menu.data.permissions);
      } else {
        this.islogin = false;
        this.$message.warning(menu.message);
        return false;
      }

      this.$router.replace({
        path: '/',
      });
      this.$message.success('Login Success 登录成功');
      this.islogin = false;
    },
    async getCaptcha() {
      var captcha = await this.$API.auth.captcha.get().catch(() => {
        this.islogin = false;
      });
      if (captcha != null) {
        this.captchaImage = 'data:text/html;base64,' + captcha.data.base64;
        this.captchaCheckId = captcha.data.id;
      }
    },
  },
};
</script>

<style scoped>
.captcha_card {
  --el-dialog-width: 24%;
}
.login-content-code {
  display: flex;
  align-items: center;
  justify-content: space-around;

  .login-content-code-img {
    width: 100%;
    height: 40px;
    line-height: 40px;
    background-color: #ffffff;
    border: 1px solid rgb(220, 223, 230);
    cursor: pointer;
    transition: all ease 0.2s;
    border-radius: 4px;
    user-select: none;

    &:hover {
      border-color: #c0c4cc;
      transition: all ease 0.2s;
    }
  }
}
</style>
